package com.freesky.quartz.task;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freesky.biz.abchina.api.AbChinaCoupon;
import com.freesky.biz.abchina.domain.TRightsOrderRecord;
import com.freesky.biz.abchina.mapper.RightsOrderMapper;
import com.freesky.biz.rights.mapper.RightsBusiMapper;
import com.freesky.common.constant.LotteryConstants;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 福建农行信用卡微信首绑首刷礼
 */
@Component("rightsOrderTask")
public class AbChinaRightsOrderTask {

    private static final Logger logger = LoggerFactory.getLogger(AbChinaRightsOrderTask.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RightsOrderMapper rightsOrderMapper;

    @Autowired
    private RightsBusiMapper rightsBusiMapper;

    @Autowired
    private AbChinaCoupon abChinaCoupon;

    public void taskProcess() {
        logger.info("AbChinaRightsOrderTask task start");
        List<TRightsOrderRecord> rightsOrderRecordList = rightsOrderMapper.selectUnPayList();
        for(TRightsOrderRecord rightsOrderRecord : rightsOrderRecordList){
            AjaxResult queryResult = abChinaCoupon.userQuery(rightsOrderRecord.getPayOrderNo());
            if(!queryResult.isSuccess()){
                continue;
            }

            String lotteryKey = StrUtil.format(LotteryConstants.LOTTERY, rightsOrderRecord.getBusiId());

            JSONObject jsonObject = JSON.parseObject(queryResult.get(AjaxResult.DATA_TAG).toString());
            rightsOrderRecord.setPayStatus(jsonObject.getString("status"));

            if(!"0".equalsIgnoreCase(rightsOrderRecord.getPayStatus())) {
                rightsOrderMapper.updatePayStatus(rightsOrderRecord);
            }

            //已取消或退款
            if("2".equalsIgnoreCase(rightsOrderRecord.getPayStatus())
                    || "4".equalsIgnoreCase(rightsOrderRecord.getPayStatus())){
                redisCache.increment(lotteryKey, "leftCoupons", 1);
                rightsBusiMapper.updateBusiCount(rightsOrderRecord.getBusiId(),-1);
            }
        }
    }

}
